package com.cheyunkeji.er.fragment.evaluate;

import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.aspsine.swipetoloadlayout.OnLoadMoreListener;
import com.aspsine.swipetoloadlayout.OnRefreshListener;
import com.cheyun.netsalev3.R;
import com.cheyun.netsalev3.widget.MyEditText;
import com.cheyunkeji.er.Constants;
import com.cheyun.netsalev3.MyApplication;
import com.cheyunkeji.er.activity.evaluate.EvaluateWorkflowActivity;
import com.cheyunkeji.er.adapter.evaluate.CarFragLvAdapter;
import com.cheyunkeji.er.base.BaseFragment;
import com.cheyunkeji.er.bean.evaluate.EvaluateCarItemInfo;
import com.cheyunkeji.er.bean.event.RefreshUIEvent;
import com.cheyunkeji.er.http.ApiClient;
import com.cheyunkeji.er.http.HttpConstants;
import com.cheyunkeji.er.http.RespCallback;
import com.cheyunkeji.er.view.SDialog;
import com.cheyunkeji.er.view.SToast;
import com.cheyunkeji.er.view.SwipeLayout;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Request;

/** Created by Michael on 2017/3/15 17:15. */
public class CarFragment extends BaseFragment
    implements OnRefreshListener,
        OnLoadMoreListener,
        TextWatcher,
        CarFragLvAdapter.OnSwipeMenuClickedListener,
        SDialog.SDialog2Listener {

  private static final String TAG = CarFragment.class.getSimpleName();

  //    每页数据量
  private static final int COUNTS_PER_PAGE = 10;

  //    删除成功
  private static final int DELETE_OK = 0x11;

  //    上传成功
  private static final int UPLOAD_OK = 0x12;

  //    当前列表状态 STATE_REFRESH : 下拉刷新 ，STATE_LOADMORE : 上拉加载更多
  private static int CURRENT_REFRESH_STATE = SwipeLayout.STATE_REFRESH;

  //     当前页数
  private static int CURRENT_LOAD_PAGE = 1;

  //    搜索关键字
  private static String KEY_WORDS = null;

  @BindView(R.id.vTitle)
  TextView vTitle;

  @BindView(R.id.vRight)
  TextView vRight;

//  @BindView(R.id.iv_search)
//  ImageButton ivSearch;

//  @BindView(R.id.et_search_content)
//  EditText etSearchContent;

  @BindView(R.id.et_search_content)
  MyEditText etSearchContent;

  @BindView(R.id.tv_search_content)
  TextView tvSearchContent;

  @BindView(R.id.ll_empty_content_display)
  LinearLayout llEmptyContentDisplay;

  @BindView(R.id.swipe_target)
  ListView lvCarList;

  @BindView(R.id.swipe_layout)
  SwipeLayout swipeLayout;

  @BindView(R.id.tv_item_count)
  TextView tvItemCount;

  private SDialog dialog, singleDialog;
  private ArrayList<EvaluateCarItemInfo> dataList;

  private CarFragLvAdapter adapter;

  private Handler uiRefreshHandler =
      new Handler() {

        @Override
        public void handleMessage(Message msg) {

          switch (msg.what) {
            case SwipeLayout.STATE_NORMAL:
              if (CURRENT_REFRESH_STATE == SwipeLayout.STATE_REFRESH) {
                onRefreshSuccessed((ArrayList<EvaluateCarItemInfo>) msg.obj);
              } else {
                onLoadMoreSuccessed((ArrayList<EvaluateCarItemInfo>) msg.obj);
              }
              break;
            case SwipeLayout.STATE_SEARCH_BY_KEYWORD:
              if (CURRENT_REFRESH_STATE == SwipeLayout.STATE_REFRESH) {
                onRefreshSuccessed((ArrayList<EvaluateCarItemInfo>) msg.obj);
              } else {
                onLoadMoreSuccessed((ArrayList<EvaluateCarItemInfo>) msg.obj);
              }
              break;
            case UPLOAD_OK:
            case DELETE_OK:
              swipeLayout.setRefreshing(true);
              onRefresh();
              break;
            default:
              break;
          }
        }
      };
  private String remindStr;
  private String aid;

  /**
   * 上拉加载成功刷新
   *
   * @param newList
   */
  private void onLoadMoreSuccessed(ArrayList<EvaluateCarItemInfo> newList) {
    if (newList != null) {
      if (newList.size() != 0) {
        swipeLayout.endLoadMore();
        dataList.addAll(newList);
        adapter.notifyDataSetChanged();
        CURRENT_LOAD_PAGE++;
      } else {
        swipeLayout.endLoadMore();
        swipeLayout.setLoadMoreEnabled(false);
      }
    }
  }

  private void onRefreshSuccessed(ArrayList<EvaluateCarItemInfo> newList) {
    if (newList != null && newList.size() != 0) {
      hideEmptyView();
      dataList.clear();
      dataList.addAll(newList);
      adapter.notifyDataSetChanged();
      CURRENT_LOAD_PAGE++;
    } else if (newList.size() == 0) {
      showContentEmptyView();
      dataList.clear();
      adapter.notifyDataSetChanged();
    }
    swipeLayout.endRefresh();
  }

  public void showRemind(String remindStr, String aid) {
    this.remindStr = remindStr;
    this.aid = aid;
    if (null == singleDialog) {
      singleDialog =
          new SDialog(
              this.getActivity(),
              "温馨提示",
              remindStr,
              R.string.t_supplement,
              R.string.t_cancel,
              new SDialog.SDialog2Listener() {
                @Override
                public void onClick(boolean l, View view) {
                  //                    true：左按钮 false：右按钮
                  if (l) {
                    JumpView();
                  }
                }
              });
    } else {
      singleDialog.setContent(remindStr);
    }
    singleDialog.show();
  }

  /** 切换界面 */
  private void JumpView() {
    String[] strings = remindStr.split("\\.");
    if (strings.length > 1) {
      final int index = Integer.parseInt(strings[0]) - 1;
      Intent intent = new Intent(getActivity(), EvaluateWorkflowActivity.class);
      intent.putExtra("AID", aid);
      intent.putExtra("index", index);
      intent.putExtra(
          Constants.EVALUATE_ARCHIVE_TYPE, Constants.ARCHIVE_TYPE_UN_UPLOAD_TO_EVALUATE);
      startActivity(intent);
    } else {
      Intent intent = new Intent(getActivity(), EvaluateWorkflowActivity.class);
      intent.putExtra("AID", aid);
      intent.putExtra(
          Constants.EVALUATE_ARCHIVE_TYPE, Constants.ARCHIVE_TYPE_UN_UPLOAD_TO_EVALUATE);
      startActivity(intent);
    }
  }

  @Override
  protected void doInflaterView(LayoutInflater inflater, ViewGroup container) {
    contentView = inflater.inflate(R.layout.er_frag_car, container, false);
    ButterKnife.bind(this, contentView);
  }

  @Override
  protected void init() {
    KEY_WORDS = "";
    dataList = new ArrayList<>();
    adapter = new CarFragLvAdapter(dataList, getActivity());
    lvCarList.setAdapter(adapter);
  }

  @Override
  protected void initView() {
//    ivSearch.setOnClickListener(this);
    vRight.setOnClickListener(this);
    swipeLayout.setOnRefreshListener(this);
    swipeLayout.setOnLoadMoreListener(this);
    etSearchContent.addTextChangedListener(this);
    dialog =
        new SDialog(
            this.getActivity(),
            R.string.t_message_title,
            true,
            getResources().getString(R.string.make_sure_to_delete),
            this,
            SDialog.TYPE_2_BTN);
    etSearchContent.setOnEditorActionListener(new TextView.OnEditorActionListener() {
      @Override
      public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_UNSPECIFIED) {
          KEY_WORDS = etSearchContent.getText().toString().trim();
          swipeLayout.setRefreshing(true);
          onRefresh();
          return true;
        } else {
          return false;
        }
      }
    });

  }

  @Override
  protected void initData() {}

  @Override
  public void onResume() {
    super.onResume();
    swipeLayout.setRefreshing(true);
    onRefresh();
  }

  private void loadSavedEvaluateCarList(int page, int rows, final String keyWord) {
    HashMap<String, String> params = new HashMap<>();
    //      params.put("authkey",
    // UserInfoManager.getInstance(MyApplication.getInstance()).getAuthKey());//
    // params.put(ChannelInfoUtil.getCurrentChannelInfo().getCkey1().getYkey(),
    // ChannelInfoUtil.getCurrentChannelInfo().getCkey1().getY7e_e73a691f02a46500201c3998e6a2989d());
    params.put("page", String.valueOf(page));
    params.put("rows", String.valueOf(rows));
    params.put("state", "1");
    if (!TextUtils.isEmpty(keyWord)) params.put("key", keyWord);

    ApiClient.postForm(
        HttpConstants.EVALUATE_CAR_LIST,
        params,
        new RespCallback<List<EvaluateCarItemInfo>>() {

          @Override
          protected void onRequestFailed(String msg) {
            SToast.show(msg, Gravity.CENTER);
          }

          @Override
          protected void onMsgCount(int rows) {
            super.onMsgCount(rows);
            //                发送广播通知“我的”页面更新分类数据项
            notifyRefreshItemCounts();
            setItemCount(rows);
          }

          @Override
          protected void onSuccess(List<EvaluateCarItemInfo> data) {

            Message msg = uiRefreshHandler.obtainMessage();
            msg.what =
                TextUtils.isEmpty(keyWord)
                    ? SwipeLayout.STATE_NORMAL
                    : SwipeLayout.STATE_SEARCH_BY_KEYWORD;
            msg.obj = data;
            uiRefreshHandler.sendMessage(msg);
          }

          @Override
          public void onError(Exception e) {
            super.onError(e);

            if (CURRENT_REFRESH_STATE == SwipeLayout.STATE_REFRESH) {
              swipeLayout.endRefresh();
            } else if (CURRENT_REFRESH_STATE == SwipeLayout.STATE_LOADMORE) {
              swipeLayout.endLoadMore();
            }
          }
        });
  }

  /** 评估项状态发生变化时，通知我的页面数量显示更新 */
  private void notifyRefreshItemCounts() {
    EventBus.getDefault()
        .postSticky(new RefreshUIEvent(RefreshUIEvent.TYPE_REFRESH_EVALUATE_MINE_ITEM_COUNTS));
  }

  @Override
  public void onClick(View v) {

    switch (v.getId()) {
//      case R.id.iv_search:
//        KEY_WORDS = etSearchContent.getText().toString().trim();
//        swipeLayout.setRefreshing(true);
//        onRefresh();
//        break;
      case R.id.vRight:
        MyApplication.getInstance().clearEvaluateResult();
        Intent intent = new Intent(getActivity(), EvaluateWorkflowActivity.class);
        intent.putExtra(
            Constants.EVALUATE_ARCHIVE_TYPE, Constants.ARCHIVE_TYPE_CREATE_NEW_EVALUATE);
        startActivity(intent);
        break;
      default:
        break;
    }
  }

  private void hideEmptyView() {
    // swipeLayout.setVisibility(View.VISIBLE);
    llEmptyContentDisplay.setVisibility(View.INVISIBLE);
  }

  private void showContentEmptyView() {
    // swipeLayout.setVisibility(View.INVISIBLE);
    if (!TextUtils.isEmpty(KEY_WORDS)) {
      llEmptyContentDisplay.setVisibility(View.VISIBLE);
      tvSearchContent.setText(KEY_WORDS);
    } else {
      llEmptyContentDisplay.setVisibility(View.INVISIBLE);
    }
  }

  @Override
  public void onLoadMore() {
    CURRENT_REFRESH_STATE = SwipeLayout.STATE_LOADMORE;
    loadSavedEvaluateCarList(CURRENT_LOAD_PAGE, COUNTS_PER_PAGE, KEY_WORDS);
  }

  @Override
  public void onRefresh() {
    CURRENT_REFRESH_STATE = SwipeLayout.STATE_REFRESH;
    CURRENT_LOAD_PAGE = 1;
    loadSavedEvaluateCarList(CURRENT_LOAD_PAGE, COUNTS_PER_PAGE, KEY_WORDS);
    swipeLayout.setLoadMoreEnabled(true);
  }

  @Override
  public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

  @Override
  public void onTextChanged(CharSequence s, int start, int before, int count) {}

  @Override
  public void afterTextChanged(Editable s) {
    if (TextUtils.isEmpty(s.toString())) {
      KEY_WORDS = null;
    }
  }

  @Override
  public void onDestroy() {
    super.onDestroy();
    uiRefreshHandler.removeCallbacksAndMessages(null);
  }

  @Override
  public void onItemClicked(int position) {
    Intent intent = new Intent(getActivity(), EvaluateWorkflowActivity.class);
    intent.putExtra("AID", dataList.get(position).getAid());
    intent.putExtra(Constants.EVALUATE_ARCHIVE_TYPE, Constants.ARCHIVE_TYPE_UN_UPLOAD_TO_EVALUATE);
    startActivity(intent);
    Log.e(TAG, "onItemClicked: " + dataList.get(position).getAid());
  }

  public void setItemCount(int itemCount) {
    tvItemCount.setText(String.format("共%1$s条数据", String.valueOf(itemCount)));
  }

  @Override
  public void onUploadClicked(int position) {
    deleteOrUploadSpecifiedItem(
        dataList.get(position).getAid(), position, HttpConstants.UPLOAD_EVALUATE_ITEM_BY_AID);
  }

  @Override
  public void onDeleteClicked(int position) {
    dialog.setTag(position);
    dialog.show();
  }

  private void deleteOrUploadSpecifiedItem(
      final String aid, final int position, final String httpUrl) {
    HashMap<String, String> params = new HashMap<>();
    //      params.put("authkey",
    // UserInfoManager.getInstance(MyApplication.getInstance()).getAuthKey());//
    // params.put(ChannelInfoUtil.getCurrentChannelInfo().getCkey1().getYkey(),
    // ChannelInfoUtil.getCurrentChannelInfo().getCkey1().getY7e_e73a691f02a46500201c3998e6a2989d());
    params.put("aid", aid);
    ApiClient.postForm(
        httpUrl,
        params,
        new StringCallback() {

          @Override
          public void onError(Call call, Exception e, int id) {
            // 网络异常
            if (e instanceof UnknownHostException || e instanceof SocketException) {
              SToast.show(R.string.tip_network_error, Gravity.CENTER);
              return;
            }

            if (HttpConstants.DELETE_EVALUATE_ITEM_BY_AID.equals(httpUrl)) {
              SToast.show("删除失败");
            } else {
              SToast.show("上传失败");
            }
          }

          @Override
          public void onResponse(String response, int id) {
            try {
              JSONObject obj = new JSONObject(response);
              if (1 == obj.optInt("code", 0)) {

                if (HttpConstants.DELETE_EVALUATE_ITEM_BY_AID.equals(httpUrl)) {
                  SToast.show("删除成功");
                  Message msg = uiRefreshHandler.obtainMessage();
                  msg.obj = position;
                  msg.what = DELETE_OK;
                  uiRefreshHandler.sendMessage(msg);

                } else {
                  SToast.show("上传成功");
                  Message msg = uiRefreshHandler.obtainMessage();
                  msg.obj = position;
                  msg.what = UPLOAD_OK;
                  uiRefreshHandler.sendMessage(msg);
                }
                notifyRefreshItemCounts();
              } else {
                showRemind(obj.optString("msg"), aid);
              }

            } catch (JSONException e) {
              e.printStackTrace();
            }
          }

          @Override
          public void onBefore(Request request, int id) {
            showDialog();
          }

          @Override
          public void onAfter(int id) {
            dismissDialog();
          }
        });
  }

  @Override
  public void onClick(boolean l, View view) {
    if (view.getId() != R.id.ok && !l) {
      deleteOrUploadSpecifiedItem(
          dataList.get(dialog.getTag()).getAid(),
          dialog.getTag(),
          HttpConstants.DELETE_EVALUATE_ITEM_BY_AID);
    }
  }
}
